package web

import (
	"context"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

type HelloServiceImpl struct {
}

func (s *HelloServiceImpl) Hello(ctx context.Context, req *String) (*String, error) {
	return &String{Value: "server Hello response: " + req.Value}, nil
}

func (s *HelloServiceImpl) mustEmbedUnimplementedHelloServiceServer() {}

func (s *HelloServiceImpl) Auth(ctx context.Context) error {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return fmt.Errorf("missing credentials")
	}

	var user string
	var password string

	if val, ok := md["user"]; ok {
		user = val[0]
	}

	if val, ok := md["password"]; ok {
		password = val[0]
	}

	if user != "admin" || password != "admin" {
		return status.Errorf(codes.Unauthenticated, "token 不合法")
	}

	fmt.Println("用户密码验证成功")

	return nil
}
